"""Docutils HTML Writer for Selenium tests.

Converts a restructed text document of paragraphs and blockquotes into
an HTML table of Selenium commands.
"""
__docformat__ = 'reStructuredText'

import docutils.writers.html4css1


class Writer(docutils.writers.html4css1.Writer):

    supported = ('selenium')

    def __init__(self):
        docutils.writers.html4css1.Writer.__init__(self)
        self.translator_class = HTMLTranslator


class HTMLTranslator(docutils.writers.html4css1.HTMLTranslator):

    def __init__(self, document):
        docutils.writers.html4css1.HTMLTranslator.__init__(self, document)
        self.have_visited_first_paragraph = False

    def depart_document(self, node):
        self.fragment.extend(self.body)
        self.body_prefix.append(self.starttag(node, 'table', cellpadding="1",
                                              cellspacing="1", border="1"))
        self.body_suffix.insert(0, '</table>\n')

    def visit_paragraph(self, node):
        if self.have_visited_first_paragraph:
            self.body.append('<tr>\n<td colspan="3">\n<em>')
            self.context.append('</em>\n</td>\n</tr>\n')
        else:
            self.body.append('<tr>\n<th colspan="3">\n')
            self.context.append('\n</th>\n</tr>\n')
            self.have_visited_first_paragraph = True

    def visit_block_quote(self, node):
        self.insert_selenium_commands(node.children)
        # XXX What is the right way to avoid visiting the child nodes?
        # For now we just throw them away.
        node.children = []

    def depart_block_quote(self, node):
        pass

    def insert_selenium_commands(self, commands):
        for command in commands:
            self.body.append('<tr>\n')
            args = command.astext().split('\n')
            for td in args:
                self.body.append('<td>%s</td>\n' % td)
            for n in range(3-len(args)):
                # Empty cells
                self.body.append('<td></td>\n')
            self.body.append('</tr>\n')

